// 封装axios请求
import qs from 'qs'
import service from '@/common/config/axiosConfig'

const httpService = {
  /**
   * 查询
   * @param url
   * @param params
   * @returns {Promise<AxiosResponse<any>>}
   */
  get (url, params) {
    return service.get(url, {
      params: params,
      paramsSerializer: (params) => {
        return qs.stringify(params)
      }
    })
  },
  /**
   * 查询（restful风格）
   * @param url
   * @param params
   * @returns {Promise<AxiosResponse<any>>}
   */
  getOfRestful (url, params) {
    let _params
    if (Object.is(params, null)) {
      _params = ''
    } else {
      _params = '/'
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== '') {
          _params += `${params[key]}/`
        }
      }
      _params = _params.substr(0, _params.length - 1)
    }
    if (_params) {
      return service.get(`${url}${_params}`)
    } else {
      return service.get(url)
    }
  },
  /**
   * 新增
   * @param url
   * @param params
   * @returns {Promise<AxiosResponse<any>>}
   */
  post (url, params) {
    return service.post(url, params, {
      transformRequest: [(params) => {
        return JSON.stringify(params)
      }],
      headers: { 'Content-Type': 'application/json' }
    })
  },
  /**
   * 修改
   * @param url
   * @param params
   * @returns {Promise<AxiosResponse<any>>}
   */
  put (url, params) {
    return service.put(url, params, {
      transformRequest: [(params) => {
        return JSON.stringify(params)
      }],
      headers: { 'Content-Type': 'application/json' }
    })
  },
  /**
   * 删除
   * @param url
   * @param params
   * @returns {Promise<AxiosResponse<any>>}
   */
  delete (url, params) {
    let _params
    if (Object.is(params, null)) {
      _params = ''
    } else {
      _params = '/'
      for (const key in params) {
        // eslint-disable-next-line no-prototype-builtins
        if (params.hasOwnProperty(key) && params[key] !== null && params[key] !== '') {
          _params += `${params[key]}/`
        }
      }
      _params = _params.substr(0, _params.length - 1)
    }
    if (_params) {
      return service.delete(`${url}${_params}`).catch(err => {
        message.error(err.msg)
        return Promise.reject(err)
      })
    } else {
      return service.delete(url).catch(err => {
        message.error(err.msg)
        return Promise.reject(err)
      })
    }
  }
}

export default httpService
